var working = false;
var file = null;
var opts = null;
var temp = null;
var record = {
	idx:'',
	time: '',
	src_url: '',
	dst_url: '',
	browser_oper:'',
	key_act:'',
	mouse_act:''
}
var current_idx = 0;
var last_key_code = 0;
var hooks_lst = {
	//function hooks
	functions: {
		BrowserBack: { 
			callback: ued_back_hook_cb,
			old_callback: function(){}
		},
		BrowserForward: {
			callback: ued_forward_hook_cb,
			old_callback: function(){}
		},
		BrowserReload: {
			callback: ued_reload_hook_cb, 
			old_callback: function(){}
		},
		BrowserStop: { 
			callback: ued_stop_hook_cb, 
			old_callback: function(){}
		},
		BrowserGoHome: {
			callback: ued_home_hook_cb,
			old_callback: function(){}
		}
	},
	//obj event hooks
	//obj-name : behavior : callback
	events: [
		['$', 'mouseup', ued_mouse_click_hook_cb],
		['$', 'keypress', ued_key_press_hook_cb],
		['$', 'DOMContentLoaded', ued_page_load_hook_cb]
	]
};


function ued_menu_cb(btn) {
	if (btn) { //Right Click, pop menu
		document.getElementById("ued_menu").showPopup(
			document.getElementById("ued_bar_label"),
			-1, -1, "popup", "topright", "bottomright");
	} else {
		ued_work();
	} 
}

function ued_register_hooks() {
	var params = hooks_lst.events[0];
	var obj = params[0] == '$'? window: $(params[0]);
	opts['hook_mouse']? obj.addEventListener(params[1], params[2], false): null;

	params = hooks_lst.events[1];
	obj = params[0] == '$'? window: $(params[0]);
	opts['hook_key']? obj.addEventListener(params[1], params[2], false): null ;

	params = hooks_lst.events[2];
	obj = params[0] == '$'? window: $(params[0]);
	opts['hook_page']? obj.addEventListener(params[1], params[2], false): null;
	

	hooks_lst.functions.BrowserBack.old_callback = eval(BrowserBack);
	BrowserBack = opts['hook_back']? function () {
		hooks_lst.functions.BrowserBack.callback(); hooks_lst.functions.BrowserBack.old_callback();
		return true;
	}: BrowserBack;

	hooks_lst.functions.BrowserForward.old_callback = eval(BrowserForward);
	BrowserForward =opts['hook_forward']? function () {
		hooks_lst.functions.BrowserForward.callback(); hooks_lst.functions.BrowserForward.old_callback();
		return true;
	}: BrowserForward;

	hooks_lst.functions.BrowserStop.old_callback = eval(BrowserStop);
	BrowserStop = opts['hook_stop']? function () {
		hooks_lst.functions.BrowserStop.callback(); hooks_lst.functions.BrowserStop.old_callback(); 
		return true;
	}: BrowserStop;

	hooks_lst.functions.BrowserReload.old_callback = eval(BrowserReload);
	BrowserReload = opts['hook_reload']? function () {
		hooks_lst.functions.BrowserReload.callback(); hooks_lst.functions.BrowserReload.old_callback(); 
		return true;
	}: BrowserReload;

	hooks_lst.functions.BrowserGoHome.old_callback = eval(BrowserGoHome);
	BrowserGoHome = opts['hook_home']? function () {
		hooks_lst.functions.BrowserGoHome.callback(); hooks_lst.functions.BrowserGoHome.old_callback(); 
		return true;
	}: BrowserGoHome;

}

function ued_unregister_hooks() {
	for (var k in hooks_lst.events) {
		var params = hooks_lst.events[k];
		var obj = params[0] == '$'? window: $(params[0]);
		obj.removeEventListener(params[1], params[2], false);
	}
	BrowserBack =   hooks_lst.functions.BrowserBack.old_callback;
	BrowserForward= hooks_lst.functions.BrowserForward.old_callback;
	BrowserStop =   hooks_lst.functions.BrowserStop.old_callback;
	BrowserReload = hooks_lst.functions.BrowserReload.old_callback;
	BrowserGoHome = hooks_lst.functions.BrowserGoHome.old_callback;
}


function ued_about() {
	window.open('http://www.sxnsx.com/uedigger/');
}

function ued_show_preferences() {
	window.openDialog("chrome://UEDigger/content/preferences_dialog.xul");
}

function ued_work(){
	if (!working) {
		current_idx = 0;
		opts = ued_prefs.load();
		//direct operation system
		var os = Components.classes["@mozilla.org/xre/app-info;1"]
                .getService(Components.interfaces.nsIXULRuntime).OS;
		var p = os.search("WINNT")==-1?"/":"\\";
		
		var now_time = new Date();
		var logfile = '' + now_time.getFullYear() 
					+ now_time.getMonth()
					+ now_time.getDate() 
					+ now_time.getHours() 
					+ now_time.getMinutes() 
					+ now_time.getSeconds();
	

		//init log file
		var log_path = opts["log_path"] + p + logfile + ".log"; //"/home/shellex/Desktop/uedigger.log";
		file = Components.classes["@mozilla.org/file/local;1"]
						 .createInstance(Components.interfaces.nsILocalFile);
		file.initWithPath(log_path);
		record.browser_oper = "BrowserStart";
		ued_log();
		if (!file.exists()) {
			alert("File/Path doesn't exitst, plz choose a path to store logfile");
			window.openDialog("chrome://UEDigger/content/preferences_dialog.xul");
			return;
		}
		ued_register_hooks();
	} else {
		ued_unregister_hooks();
	}
	working = !working;
	$('ued_bar_label').value = (working? "UED:Working": "UED:Stop");
}


// hooks proc...
function ued_back_hook_cb(event){
	record.browser_oper = 'BrowserBack';
	record.src_url = window.content.document.referrer;
	record.dst_url = $('urlbar').value;
	//ued_log();
	return true;	
}

function ued_forward_hook_cb(event){
	record.browser_oper = 'BrowserForward';
	record.src_url = window.content.document.referrer;
	record.dst_url = $('urlbar').value;
	//ued_log();
	return true;	
}

function ued_reload_hook_cb(event){
	record.browser_oper = 'BrowserReload';
	record.src_url = window.content.document.referrer;
	record.dst_url = $('urlbar').value;
	//ued_log();
	return true;	

}

function ued_stop_hook_cb(event){
	record.browser_oper = 'BrowserStop';
	record.src_url = window.content.document.referrer;
	record.dst_url = $('urlbar').value;
	//ued_log();
	return true;	
}

function ued_home_hook_cb(event){
	record.browser_oper = 'BrowserGoHome';
	record.src_url = window.content.document.referrer;
	record.dst_url = $('urlbar').value;
	//ued_log();
	return true;	
}

function ued_page_load_hook_cb(event){
	record.src_url = window.content.document.referrer;
	record.dst_url = $('urlbar').value;
	ued_log();
}

function ued_mouse_click_hook_cb(event){
	if (record.browser_oper == '') {
		record.mouse_act = event.pageX + ',' + event.pageY;
	}
}

function ued_key_press_hook_cb(event){
	if (event.charCode <= 126 && 32 <= event.charCode) {
		last_key_code = event.charCode + 255;
	} else {
		last_key_code = event.keyCode;
	}

	record.key_act += ':' + last_key_code; 
}

	

// write to logfile
function ued_log() {
	//ignore page partially reload
	if (record.browser_oper == '' && record.key_act == ''
		&& record.mouse_act == '' && src_url == '')
		return;

	var now_time = new Date();
	time =  now_time.getHours()
		+ ':' + now_time.getMinutes() 
		+ ':' + now_time.getSeconds() ;
	current_idx += 1;
	record.idx = current_idx;
	record.time = time;
		
	var str = '';
	for (var each in record) {
		str += record[each] + '\n';
		record[each] = '';
	}
	str += '\n';

	// file is nsIFile, data is a string
	var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);

	// use 0x02 | 0x08 | 0x10  to open file for write, append and create.
	foStream.init(file, 0x02 | 0x08 | 0x10, 0666, 0); 
	foStream.write(str, str.length);
	foStream.close();
}




